'''
Created on 2009-12-28

@author: Madlee
'''

import sqlite3
from kuai.pim.dateterm import extract_time


SQL_CREATE_TABLE = [
"""CREATE TABLE IF NOT EXISTS 'KUAI_PIM_DOCUMENTS'
    (id             INTEGER PRIMARY KEY AUTOINCREMENT,
     content        TEXT DEFAULT '',
     create_time    DATETIME DEFAULT CURRENT_TIMESTAMP,
     modify_time    DATETIME DEFAULT CURRENT_TIMESTAMP);""",
"""CREATE TABLE IF NOT EXISTS 'KUAI_PIM_SCHEDULE'
    (id             INTEGER PRIMARY KEY AUTOINCREMENT,
     document       INTEGER REFERENCES 'KUAI_PIM_DOCUMENTS',
     schedule       DATETIME);""",
]

SQL_INSERT_DOCUMENT = ["INSERT INTO KUAI_PIM_DOCUMENTS (content) VALUES (?)",
                       "SELECT MAX(id) FROM KUAI_PIM_DOCUMENTS"]

class Database:
    def __init__(self, filename):
        self.__conn = sqlite3.connect(filename)
        cursor = self.__conn.cursor()
        for i in SQL_CREATE_TABLE:
            cursor.execute(i)
        self.__conn.commit()
        cursor.close()
        
    def save_schedule(self, content, id=None):
        id = self.save_document(content, id)
        # TODO
                
    
    def save_document(self, content, id=None):
        cursor = self.__conn.cursor()
        if id is None:
            cursor.execute(SQL_INSERT_DOCUMENT[0], content)
            self.__conn.commit()
            cursor.execute(SQL_INSERT_DOCUMENT[1], content)
                        
        cursor.close()
